#! -*- coding:utf-8 -*-
import logging
from datetime import datetime, timedelta
from django.core.management.base import BaseCommand
from common.order import admin_db as order_db
from pymongo import MongoClient
from django.conf import settings
from common.channel.admin_db import get_channels_in_ids

_LOGGER = logging.getLogger(__name__)


class Command(BaseCommand):
    # 参数描述 days：生成今天之前第n天的通道统计参数
    def handle(self, n_days_before, **options):
        n = int(n_days_before)
        now = datetime.utcnow() + timedelta(hours=8)
        start = datetime.strptime("{}-{}-{} 0:0:0".format(now.year, now.month, now.day), "%Y-%m-%d %H:%M:%S")
        start = start + timedelta(days=-n)
        end = (start + timedelta(days=1))

        query_dct = {'status': '2'}
        query_dct['created_at'] = '''{"$gte":"''' + start.strftime('%Y-%m-%d %H:%M:%S') + '''","$lt":"''' \
                                  + end.strftime('%Y-%m-%d %H:%M:%S') + '''"}'''

        print 'start query_dct'
        items, total_count = order_db.list_order(query_dct)  # 必须保留
        overview, chn_ids = order_db.get_order_overview(query_dct)
        print len(chn_ids)
        chns = get_channels_in_ids(chn_ids)
        p_info = dict()
        for chn in chns:
            p_info[chn.id] = {
                'name': chn.name,
                'service_name': chn.service_name,
                'mch_id': chn.mch_id,
            }

        mg = MongoClient(settings.MONGO_ADDR).paychannel_stat
        for o in overview:
            chn_id = o['channel_id']
            if chn_id not in p_info:
                continue
            chn_info = p_info[chn_id]
            o.update({
                'channel_name': chn_info['name'],
                'service_name': chn_info['service_name'],
                'mch_id': chn_info['mch_id'],
                'start': start,
                'end': end,
            })
            id = str(o['channel_id']) + start.strftime('_%Y%m%d')
            mg.channel_status.update_one({'_id': id}, {'$set': o}, upsert=True)

